<template>
  <div class="uploadImg">
    <!--
   el-upload
      action:上传地址，它是必传
      name:'上传文件的字段名（接口字段名）'
      before-upload:上传前回调,限制 上传文件大小与类型  需要return  boolean值  true:正常上传，false:中止上传
      on-success:上传成功的回调
      http-request:自定义上传,它会替换以前上传默认行为（action无效，on-success也无效）
      show-file-list：是否显示文件列表

  腾讯云上传使用
  1：安装插件
     cos-js-sdk-v5   yarn add  cos-js-sdk-v5
  2:导入
    import Cos from 'cos-js-sdk-v5'
  3:实例化
  let cos = new Cos({
    SecretId: 'COS_SECRETID', // 身份识别 ID
    SecretKey: 'COS_SECRETKEY', // 身份密钥
});
  4:使用
  cos.putObject({
    Bucket: 'dhf481229-1305249343', /* 存储桶: */
    Region: 'ap-guangzhou',     /* 存储桶所在地域，必须字段 */
    Key: uid+'',              /* 必须是字符串 */
    StorageClass: 'STANDARD',  // 固定值
    Body: 文件对象, // 上传文件对象
    onProgress: (progressData)=> {
        上传进度
        console.log(JSON.stringify(progressData));
    }
}, (err, data)=> {
  // 上传成功或者失败的回调
    console.log(err || data);
});

 -->
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="httpRequest"
    >
      <img
        v-if="imageUrl"
        v-imgError="defaultImg"
        :src="imageUrl"
        class="avatar"
        @click.stop="showBigImage"
      >
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
    <div v-if="imageUrl" class="close" @click="closeEvent">X</div>
    <!-- 预览图片 -->
    <el-dialog :visible.sync="isShow" title="图片预览">
      <div style="text-align: center">
        <img class="img" :src="imageUrl" alt="">
      </div>
    </el-dialog>
    <!-- 进度条 0-100-->
    <!--
   动画：
     条件：进入、离开动作
     实现
        1：用transition包住
        2:加上name="xxx"就是css的前缀
          .xxx-enter-active:进入过程中一直存在，进入动画的执行体，用于承载transition,animation
          .xxx-leave-active:离开过程中一直存在，离开动画的执行体，用于承载transition,animation
          .xxx-enter:进入前状态，进入前希望从什么状态变到正常状态
          .xxx-leave-to:离开时状态，离开时希望从正常状态变到什么状态

     -->
    <transition name="xxx">
      <el-progress v-if="showProgress" :percentage="percentage" />
    </transition>
  </div>
</template>
<script>
import Cos from 'cos-js-sdk-v5'
const cos = new Cos({
  SecretId: 'AKIDNXR8bpeSF1JL8EyZopxRfdHgqGUeuEn8',
  SecretKey: 'HJ9mAbQEn7jgjY9swEI6yAamk7MN8hty'
})
export default {
  name: 'UploadImg',
  model: {
    prop: 'imageUrl'
  },
  props: {
    imageUrl: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      percentage: 0,
      showProgress: false,
      isShow: false,
      defaultImg: require('@/assets/common/head.jpg')
      //   imageUrl: ''
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      console.log(file)
      // 上传前，限制 文件大小与类型
      const isPng = file.type === 'image/png' || file.type === 'image/jpeg'
      const limit1M = file.size / 1024 / 1024 < 1
      if (!isPng) {
        this.$message.error('请上传png图片')
      }
      if (!limit1M) {
        this.$message.error('请上传1M内图片')
      }
      return isPng && limit1M
    },
    httpRequest(res) {
      // 显示上传进度
      this.showProgress = true
      this.percentage = 0
      // res.file:上传文件对象
      console.log(res)
      cos.putObject(
        {
          Bucket: 'dhf481229-1305249343' /* 存储桶: */,
          Region: 'ap-guangzhou' /* 存储桶所在地域，必须字段 */,
          Key: res.file.uid + '' /* 必须是字符串 */,
          StorageClass: 'STANDARD', // 固定值
          Body: res.file, // 上传文件对象
          onProgress: (progressData) => {
            // 上传进度
            this.percentage = progressData.percent * 100
            // progressData.percent=1上传完成
            if (progressData.percent === 1) {
              setTimeout(() => {
                this.showProgress = false
              }, 1000)
            }
            console.log(JSON.stringify(progressData))
          }
        },
        (err, data) => {
          // 上传成功或者失败的回调
          console.log(err || data)
          console.log('this', this)
          //   this.imageUrl = 'http://' + data.Location
          this.$emit('input', 'http://' + data.Location)
        }
      )
    },
    // 删除图片功能
    closeEvent() {
      this.$emit('input', '')
    },
    showBigImage() {
      // 图片点击处理
      this.isShow = true
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.uploadImg {
  position: relative;
  width: 178px;
  &:hover {
    .close {
      display: block;
    }
  }
  .close {
    display: none;
    position: absolute;
    top: 5px;
    right: 10px;
    cursor: pointer;
  }
  .img {
    width: 100%;
  }
}
.xxx-enter-active,
.xxx-leave-active {
  transition: all 0.5s;
}
.xxx-enter,
.xxx-leave-to {
  opacity: 0;
}
</style>
